#!/usr/bin/env perl
if (!$::Driver) { use FindBin; exec("$FindBin::Bin/bootstrap.pl", @ARGV, $0); die; }
# DESCRIPTION: Verilator: Verilog Test driver/expect definition
#
# Copyright 2023 by Wilson Snyder. This program is free software; you
# can redistribute it and/or modify it under the terms of either the GNU
# Lesser General Public License Version 3 or the Perl Artistic License
# Version 2.0.
# SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0
use IO::File;

scenarios(vlt => 1);

$Self->{sanitize} = 0;  # GCC takes too long otherwise

sub gen {
    my $filename = shift;
    my $n = shift;

    my $fh = IO::File->new(">$filename");
    $fh->print("// Generated by t_vthread.pl\n");
    $fh->print("module genmod #(int val = 0)(clk, o);\n");
    $fh->print("  input clk;\n");
    $fh->print("  output int o;\n");
    $fh->print("  always @ (posedge clk) begin\n");
    $fh->print("    o <= val;\n");
    $fh->print("  end\n");
    $fh->print("endmodule\n");
    $fh->print("module t (clk, o);\n");
    $fh->print("  input clk;\n");
    $fh->print("  output int o;\n");
    for (my $i = 0; $i < ($n + 1); ++$i) {
        $fh->print("  int r$i;\n");
        $fh->print("  genmod #(.val($i)) rm$i (.clk(clk), .o(r$i));\n");
    }
    $fh->print("  always @ (posedge clk) begin\n");
    $fh->print("    o <= r$n;\n");
    $fh->print('    $write("*-* All Finished *-*\n");', "\n");
    $fh->print('    $finish;', "\n");
    $fh->print("  end\n");
    $fh->print("endmodule\n");
}

top_filename("$Self->{obj_dir}/t_vthread.v");

gen($Self->{top_filename}, 6000);

compile(
    # use --trace to generate trace files that can be parallelized
    verilator_flags2=>["--stats --trace --verilate-jobs 2"],
    );

execute(
    check_finished => 1,
    );

file_grep($Self->{stats}, qr/Verilate jobs: 2/);

ok(1);
1;
